package io.renren.modules.avanotes.component;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import io.renren.config.BizConfig;
import io.renren.modules.avanotes.service.WorkTask4TW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author: xiaomi
 * @date: 2022/2/22
 * @description:
 */
@Component
@Slf4j
public class TimeWheelComponent {

    @Autowired
    @Qualifier(BizConfig.NETTY_TIME_WHEEL)
    private HashedWheelTimer timerWheel;

    @Autowired
    @Qualifier(BizConfig.POOL_TIME_WHEEL)
    private ThreadPoolExecutor timerPool;


    /**
     * 添加单个任务
     *
     * @param seconds
     * @param work
     */
//    public void addTask(long seconds, WorkTask4TW work) {
//        timerWheel.newTimeout(new ProduceTimerTask(work), seconds, TimeUnit.SECONDS);
//    }

    public void addTask(long seconds, Runnable work) {
        timerWheel.newTimeout(new ProduceTimerTask(work), seconds, TimeUnit.SECONDS);
    }

    class ProduceTimerTask implements TimerTask {

//        private WorkTask4TW work;
        private Runnable runnable;

//        public ProduceTimerTask(WorkTask4TW work) {
//            this.work = work;
//        }

        public ProduceTimerTask(Runnable runnable) {
            this.runnable = runnable;
        }

        @Override
        public void run(Timeout timeout) throws Exception {
            //NOTEME 使用线程池解决延迟问题
            timerPool.execute(() -> {
                //执行
                runnable.run();
                log.info("执行了时间轮任务");
            });

        }
    }

}
